package models

import (
	"errors"
	"time"
	_ "time"

	orm "go-papers/database"
)

type MomRegister struct {
	NickName string `json:"nickName" gorm:"-"` // 昵称
	Code     string `json:"code" gorm:"-"`     // 头像地址
	Password string `json:"password" gorm:"-"` // 密码
	Phone    string `json:"phone" gorm:"-"`    // 手机号

	OpenId      string `json:"openId" gorm:"-"`                   // 手机号
	MomStatus   string `json:"momStatus" gorm:"type:tinyint(1);"` // 默认 "1"
	CardNo      string `json:"cardNo" gorm:"type:varchar(128);"`  // 身份证号
	Province    string `json:"province" gorm:"type:varchar(64);"` // 省份
	City        string `json:"city" gorm:"type:varchar(64);"`     // 城市
	Area        string `json:"area" gorm:"type:varchar(128);"`    // 区域
	Address     string `json:"address" gorm:"type:varchar(255);"` // 地址
	AddressText string `json:"addressText" gorm:"-"`              // 地址
}

func (MomRegister) TableName() string {
	return "member"
}

// 创建Member
func (e *MomRegister) Create(mid int) (Member, error) {
	e.MomStatus = "1"
	var doc Member

	//密码加密
	doc.Password = e.Password
	if err := doc.Encrypt(); err != nil {
		return doc, err
	}

	noeTime := time.Now().Format("2006-01-02 15:04:05")
	//注册 创建
	mr := &MomRegisterInfo{
		RealName:    e.NickName,
		AccountName: e.Phone,
		Password:    doc.Password,
		Phone:       e.Phone,
		WxOpenid:    e.OpenId,
		MomStatus:   "1",
		CardNo:      e.CardNo,
		Province:    e.Province,
		City:        e.City,
		Area:        e.Area,
		Address:     e.Address,
		AddressText: e.AddressText,
	}

	phoneInfo, err := doc.GetByAccountName(e.Phone)
	if err == nil && phoneInfo.MemberId > 0 && phoneInfo.MemberId != mid {
		return doc, errors.New("手机号已经注册/且与当前登陆手机号不同")
	}
	//返回
	result, err := doc.RegisterMom(mr, mid)
	if err != nil {
		return doc, errors.New("发生异常：" + err.Error())
	}

	//记录log
	var memerlog MemberLog
	memerlog.LogMemberId = result.MemberId
	memerlog.LogMemerName = result.NickName
	memerlog.LogName = "用户注册社区达人"
	memerlog.CreatedAt = noeTime
	memerlog.UpdatedAt = noeTime
	memerlog.LogInfo = "注册手机号" + e.Phone + "；注册微信OpenId：" + e.OpenId + "/" + e.Password
	_, _ = memerlog.Create()

	if e.OpenId != "" {
		var thirdUser ThirdUser
		er := orm.Eloquent.Table("third_user").Where("thrid_open_id = ? ", e.OpenId).Find(&thirdUser).Error
		if er == nil && thirdUser.ThridUserId > 0 {
			var memberThird MemberThirdInfo
			//根据 第三方id 查询是否有 关联 用户od
			_, _ = memberThird.InsertUpdate(thirdUser.ThridUserId, result.MemberId)
		}
	}
	return result, nil
}
